package com.main.login.interfaces.facade;

import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class SftpUploadService {

    @Autowired
    private SftpConfig sftpConfig;

    public void uploadFile(String filePath) throws JSchException, SftpException {

        JSch.setLogger(new com.jcraft.jsch.Logger() {
            public boolean isEnabled(int level) { return true; }
            public void log(int level, String message) {
                System.out.println("JSch: " + message);
            }
        });
        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp channel = null;

        try {
            // 1. 加载私钥（从 classpath 读取）
            ClassPathResource keyResource = new ClassPathResource(sftpConfig.getPrivateKeyPath());
            jsch.addIdentity(keyResource.getFile().getAbsolutePath());
            ClassPathResource hostsResource = new ClassPathResource(sftpConfig.getKnownHostsPath());
            jsch.setKnownHosts(hostsResource.getFile().getAbsolutePath());

            // 2. 创建会话
            session = jsch.getSession(sftpConfig.getUsername(), sftpConfig.getHost(), sftpConfig.getPort());
//            session = jsch.getSession("Administrator","192.168.86.158",22);
            session.setConfig("StrictHostKeyChecking", "yes");
            // 显式指定支持的密钥类型（关键配置）
            session.setConfig("PubkeyAcceptedAlgorithms", "rsa-sha2-512,rsa-sha2-256");
            session.setConfig("server_host_key", "ecdsa-sha2-nistp256,rsa-sha2-512,rsa-sha2-256");
            session.connect(30000); // 设置超时

            // 3. 创建 SFTP 通道并连接
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();

            // 4. 上传文件（自动管理流）
            try (FileInputStream fis = new FileInputStream(filePath)) {
                channel.put(fis, sftpConfig.getRemoteDirectory()+"file.text");
                System.out.println("上传成功！");
            }
        } catch (JSchException | SftpException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 5. 确保资源释放顺序：先通道，后会话
            if (channel != null && channel.isConnected()) {
                channel.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
}